package com.zkk.dao.impl;

import com.zkk.dao.UserDao;
import com.zkk.pojo.User;
import com.zkk.utils.DruidUtil;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;

import java.util.List;

public class UserDaoImpl implements UserDao {
    private JdbcTemplate jdbcTemplate=new JdbcTemplate(DruidUtil.getDataSource());
    @Override
    public List<User> findAll() {
        List<User> query = jdbcTemplate.query("select * from user ", new BeanPropertyRowMapper<>(User.class));
        return query;
    }

    @Override
    public User login(String username, String password) {
        List<User> query = jdbcTemplate.query("select * from user where username=? and password=?", new BeanPropertyRowMapper<>(User.class), username, password);
        if(query!=null && query.size()==1){
            return query.get(0);
        }
        return null;

    }

    @Override
    public int insert(User user) {
        int update = jdbcTemplate.update("insert into user values (null,?,?,?,?,?,?,?)",  user.getUsername(), user.getPassword(), user.getGender(), user.getAge(), user.getAddress(), user.getQq(), user.getEmail());
        return update;
    }

    @Override
    public User findUserById(int id) {
        List<User> query = jdbcTemplate.query("select * from user where id=?", new BeanPropertyRowMapper<>(User.class), id);
        if(query!=null & query.size()==1){
            return query.get(0);
        }
        return null;
    }

    @Override
    public int deleteById(int id) {
        int update = jdbcTemplate.update("delete from user where id=?", id);
        return update;
    }

    //实现分页的查询

    @Override
    public List<User> findAll(int i, int pageSize) {
        List<User> query = jdbcTemplate.query("select * from user limit ?,?", new BeanPropertyRowMapper<>(User.class), i, pageSize);
        return query;
    }
    //获得总记录数.注意类是integer

    @Override
    public int count() {
        int integer = jdbcTemplate.queryForObject("select count(*) from user", Integer.class);
        return integer;
    }
}
